import pymongo
from urllib import parse

# 对用户名和密码进行编码
username = parse.quote_plus('admin')
password = parse.quote_plus('123456')
database = "s1"
host = "39.107.248.141"
port = "27017"

# 构建 MongoDB 连接字符串
connection_string = f'mongodb://{username}:{password}@{host}:{port}/{database}?authSource=admin'
# client = pymongo.MongoClient('mongodb://username:password@host:port/database?authSource=admin')

try:
    # 创建 MongoDB 客户端连接
    client = pymongo.MongoClient(connection_string)

    # 选择数据库
    db = client[database]

    # 选择集合
    collection = db['comments']
    print(collection)

    # 执行查询操作，获取所有文档
    results = collection.find({})
    print(results)

    # 遍历查询结果并打印
    a=list(results)
    print(a)
    for result in results:
        print(result)

    # 关闭 MongoDB 客户端连接
    client.close()
except Exception as e:
    print(f"发生错误: {e}")